/**
 *  所有 body - load 需要的方法
 * 
 * 
 */

const NotSafariTxt = "点击右上角按钮，然后在弹出的菜单中，点击在safari中打开，即可安装";
const pcBrowserTxt = "请使用手机扫描二维码，进行app下载";

// 执行方法
window.onload = function(){
  if(rxPlatform === 'pc') {
    let pcText = document.getElementById('pc_text');
    pcText.innerText = pcBrowserTxt;
  }
  else {
    let buttonDiv = this.document.getElementById('app_button_div')
    var button = "<button type='button' id='app_button' onclick='downloadClick()'>点击安装</button>";
    buttonDiv.innerHTML += button;

    let qs = document.getElementById('app_install_ques');
    qs.innerHTML = "<a href='#'>无法安装?</a>"

    if(rxPlatform === 'ios' && rxBrowser !== 'Safari') {
      let safariDiv = document.getElementById('safari');
      let safrai = "<div class='open_safari_tip'>"+NotSafariTxt+"</div>"
      safariDiv.innerHTML = safrai;
    }

    let content = document.getElementById('content-center'); 
    let version = "<div id='app_version'>版本：</div>"
    let build = "<div id='app_build'>build：</div>"
    let update_time = "<div id='app_update_time'>更新日期：</div>"
    let size = "<div id='app_size'>大小：</div>"
    let line = "<div class='line'></div>"
    let desc_tip = "<div class='desc_tip'>更新内容: </div>"
    let desc = "<div class='desc'><div id='app_desc'></div></div>"
    content.innerHTML = version;
    content.innerHTML += build;
    content.innerHTML += update_time;
    content.innerHTML += size;
    content.innerHTML += line;
    content.innerHTML += desc_tip;
    content.innerHTML += desc;
  }

  generateQRCode();
  readAppInfo();
}

//生成二维码
function generateQRCode() {
  // 每次执行前先清空原有的二维码
    jQuery('#app_qr').html('');

    let currentUrl = getOrigin();;
    var print = utf16to8(currentUrl); 
    // 利用jquery.qrcode在id为“app_qr”的div中生成一个canvas格式的二维码
    jQuery('#app_qr').qrcode({
      width: 70,
      height: 70,
      correctLevel: 0,
      text: print,
      background: "#E1FFFF",//背景颜色    
      foreground: "#32CD32" //前景颜色   
    });
}

// 转换中文, 避免二维码扫描出来中文是乱码的情况（此函数来自网络）
function utf16to8(str) {
  var out, i, len, c;
  out = "";
  len = str.length;
  for(i = 0; i < len; i++) {
    c = str.charCodeAt(i);
    if ((c >= 0x0001) && (c <= 0x007F)) {
      out += str.charAt(i);
    } else if (c > 0x07FF) {
      out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
      out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
      out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
    } else {
      out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
      out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
    }
  }
  return out;
}

function downloadClick () {
  if(rxPlatform === 'pc') {
    alert(pcBrowserTxt)
    return;
  }
  
  if(rxPlatform === 'android') {
    downloadApp();
  }
  else if(rxBrowser !== 'Safari') {
    alert(NotSafariTxt)
  }
  else {
    downloadApp();
  }
}

function downloadApp() {
  window.location = appInfo.url;
}